#coding=utf-8
from django.http import HttpResponse
from django.shortcuts import render_to_response
from baixinservice.models import *
from django.db import transaction
from django.views.decorators.csrf import csrf_exempt

import sys,simplejson,datetime
reload(sys)
sys.setdefaultencoding('utf8')

def json(request):

	return HttpResponse('test')

@transaction.commit_on_success
@csrf_exempt
def addDataByJson(request):
	if request.method == 'POST':
		try:
			_json = request.POST.get('jsonStr',None)

			if not _json:
				result = { 'error':u'未找到数据 not key jsonStr' }
				return HttpResponse(simplejson.dumps(result))

			_json = eval(_json)

			_ss = Store.objects.all()

			for i in xrange(len(_json)):
				_item = _json[i]

				_uid = _item.get('uid','')

				if not _uid:
					continue

				_checkObj = _ss.filter(uid = _uid)

				if len(_checkObj) > 0:
					continue 

				_s = Store()

				_s.storeName = _item.get('title','')
				_s.storePhone = _item.get('phoneNumber','')
				_s.storeAddress = _item.get('province','') + _item.get('city','') +_item.get('address','')
				_s.storeLogo = '/static/images/store01.jpg'
				_s.geo_x = _item.get('point','').get('lng','')
				_s.geo_y = _item.get('point','').get('lat','')
				_s.uid = _uid
				_s.createTime = datetime.date.today()

				_s.save()

		except Exception,e:
			transaction.rollback()
			result = { 'error':e.message or e.__str__() }
			return HttpResponse(simplejson.dumps(result))
		else:
			result = { 'success':u'数据添加成功' }
			return HttpResponse(simplejson.dumps(result))
	if request.method == 'GET':
		return HttpResponse(u'你走错地方了')

def getDataListByPage(request, page=1):
	# _page = int(page)

	# _list = Store.objects.filter(disable = 0)

	# _pageSize = 10

	# _listLen = len(_list)

	# if _listLen % _pageSize == 0 :
	# 	_maxPage = _listLen / _pageSize
	# else:
	# 	_maxPage = _listLen / _pageSize + 1

	# if _page <= 0:
	# 	_page = 1

	# if _page > _maxPage:
	# 	_page = _maxPage

	# _startNumber = (_page - 1) * _pageSize
	# _endNumber = _startNumber + _pageSize 

	# if _endNumber >= _listLen:
	# 	_endNumber = _listLen

	# _pageData = _list[_startNumber:_endNumber]
	# { 'ss':_pageData }
	return render_to_response('appSide/storeList.html')

def dataDetail(request, sotreUid):
	# try:
		_s = Store.objects.get(uid = sotreUid)

		_phoneNumber = (_s.storePhone.split(',')[0]) or _s.storePhone
		
	# except Exception,e:
	# 	return HttpResponse(e.message or e.__str__())
	# else:
		return render_to_response('appSide/storeDetail.html', { 's':_s, 'phoneNumber':_phoneNumber})